<?php
// tabele Allegro
define('ALLCATEG','allegro_category');
define('ALLCATLA','allegro_categorylang');
define('ALLOFERT','allegro_oferta');
define('ALLOFELA','allegro_ofertalang');
define('ALLOFESE','allegro_settings');

include_once 'AllegroModel.php';
require_once 'Panel/Files.php';
include_once 'AllegroExport.php';

class AllegroController extends AllegroModel{
	public $db;
	public $pageID; 	// katalog w tej stronie
	protected $database;
	protected $opc; // dane przekazane z url
	//protected $obj; // dane do przekazania w smarty
	protected $set; // dane z tabeli settings	
	protected $photoAllegroPath;
	protected $settings_allegro;
	protected $exp; // obiekt clasy eksportujacej
	protected $tpl;
	
	function __construct($opc=null){
		global $parameters,$config,$settings;
		// sciezka do plikow tpl
		// jesli zamieszczono pliki tpl dla Allegro w theme to je wczytuj
		// jesli nie to domyslne pliki z view/Allegro
		$this->tpl = (tools::_dir_exists("Allegro","../application/theme/theme_{$settings['szablon']}/{$settings['ramka_theme']}_{$settings['ramka_theme_kolor']}")) ? "theme_{$settings['szablon']}/{$settings['ramka_theme']}_{$settings['ramka_theme_kolor']}/" : "";
		$this->obj= array();
		// przekazane zmienne
		$this->opc = (is_string($config->parameters)) ? explode(',',$config->parameters) :explode(',',$opc);
		$this->obj['subdomena'] = str_replace('www.','',$_SERVER['HTTP_HOST']); 
		
		$this->pageID = $config->page;

		// sciezka do zapisu zdjec z ofert allegro
		$this->photoAllegroPath  = "../public/users/".$this->obj['subdomena']."/allegro/";
		tools::_add_folder($this->photoAllegroPath);
		// sciezka do root bazy allegro
		tools::_add_folder($parameters['allegro']['host']);
		
		
		
		// określenie nazwy bazy aukcji
		$this->database = $this->obj['subdomena'].".db";
		// przygotowanie parametrów do zalozenia bazy
		$paramAllegro = array('drivers'=>array('driver'=>'sqlite'),
							  'sqlite'=>array('host'=>$parameters['allegro']['host'],
											  'database'=>$this->database ));
		$this->db = config::getDB($paramAllegro);
		// ustawienia
		$this->settings_allegro = tools::__adodb('getAssoc',"SELECT id, wartosc FROM ".ALLOFESE,true,$this->db);
		$this->settings_allegro["tplPath"] = $this->tpl;
		
		tools::_assign("settings_allegro",$this->settings_allegro);
		
		$parameters['sqlite']['host'] = $parameters['allegro']['host'];
		$parameters['drivers']['dbinstall'] = $parameters['allegro']['dbinstall'];
		config::_instal_database($parameters['drivers']['driver'],$this->db);
		
		$this->exp = new AllegroExportController();
	}

	function __get($var){
		if (isset($this->$var) && is_readable($this->$var)) return $this->$var;
	}
	/**
	 * metoda uruchamiana z exten_body
	 * generuje kod w zainstalowanej sekcji
	 * 
	 * wybór akcji dla url: http://21w.pl/page,Allegro,opc[0],opc[1],...
	 * @return unknown_type
	 */
	public function indexAction(){
		global $objSession,$config;
		$this->pageID = $config->page;
		// definicje linków do toolbar
		$toolbar_links0 = array(',,lista_kategorii'=>array('nazwa'=>'edycja kategorii','ikona'=>'32_folder.gif'));
		$toolbar_links1 = array(',,dodaj_kategorie,0'=>array('nazwa'=>'dodaj kategorię','ikona'=>'32_new.gif'));
		$toolbar_links2 = array(",,dodaj_oferte,{$this->opc[2]}"=>array('nazwa'=>'dodaj ofertę','ikona'=>'32_new.gif'),",,edytuj_kategorie,{$this->opc[2]}"=>array('nazwa'=>'edytuj kategorię','ikona'=>'32_edit.gif'));
		$toolbar_links3 = array(",,edytuj_oferte,{$this->opc[2]}"=>array('nazwa'=>'edytuj oferte','ikona'=>'32_edit.gif'),",,exportuj_oferte,{$this->opc[2]}"=>array('nazwa'=>'exportuj kod oferty','ikona'=>'32_export.gif'),",Allegro,usunOferteKatalogu,{$this->opc[2]}"=>array('nazwa'=>'usuń ofertę','ikona'=>'32_del.gif'));
		$toolbar_links4 = array(",,oferta,{$this->opc[2]}"=>array('nazwa'=>'podgląd oferty','ikona'=>'32_podglad.gif'),",Allegro,usunOferteKatalogu,{$this->opc[2]}"=>array('nazwa'=>'usuń ofertę','ikona'=>'32_del.gif'));
		switch($this->opc[1]){
#TODO kategorie
			case 'lista_kategorii':
				tools::_display("{$this->tpl}Allegro/header.tpl");				
				if ( !$objSession->IsLoggedIn()){	tools::_redirect('zaloguj_sie.html'); return;}
				$this->toolbar($toolbar_links1);
				echo "<h2>Lista kategorii</h2>";
				AllegroModel::listaKategoriiUstawienia(0,0,$this->getCategory(),"{$this->tpl}Allegro/tree_edycja.tpl");
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				break;
				
			case 'dodaj_kategorie':
				tools::_display("{$this->tpl}Allegro/header.tpl");
				if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				$this->toolbar($toolbar_links0);
				$this->obj['pcategID'] =  $this->opc[2];
				tools::_assign('obj',$this->obj);
				tools::_display("{$this->tpl}Allegro/dodaj_kategorie.tpl");
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				break;
				

			case 'edytuj_kategorie':
				tools::_display("{$this->tpl}Allegro/header.tpl");
				if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				$this->toolbar($toolbar_links0);
				tools::_assign('obj',$this->getCategory($this->opc[2]));
				tools::_display("{$this->tpl}Allegro/edytuj_kategorie.tpl");
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				break;

#TODO oferty
			case 'lista_ofert':	
				tools::_display("{$this->tpl}Allegro/header.tpl");
				$this->toolbar($toolbar_links2);
				
					$kategorie = $this->getCategory();
					tools::_display("{$this->tpl}Allegro/header_column_left.tpl");
					AllegroModel::listaKategoriiUstawienia(0,0,$kategorie,"{$this->tpl}Allegro/tree.tpl");
					tools::_display("{$this->tpl}Allegro/footer.tpl");
					
					$this->obj['tytul'] =  $this->polozenieKategorii($this->opc[2]);
							
					$this->obj['logged'] = ( $objSession->IsLoggedIn()) ? 1: 0;
								
					tools::_assign('obj',$this->obj);
					tools::_display("{$this->tpl}Allegro/header_column_right.tpl");
					$this->listaOfert($this->opc[2]);
					tools::_display("{$this->tpl}Allegro/footer.tpl");
										
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");	
				break;
				
			case 'wyszukaj_oferty':
				tools::_display("{$this->tpl}Allegro/header.tpl");
				$this->toolbar($toolbar_links2);
				
				$kategorie = $this->getCategory();
				tools::_display("{$this->tpl}Allegro/header_column_left.tpl");
				AllegroModel::listaKategoriiUstawienia(0,0,$kategorie,"{$this->tpl}Allegro/tree.tpl");
				tools::_display("{$this->tpl}Allegro/footer.tpl");
				
				$this->obj['tytul'] =  "Wyniki wyszukiwania dla hasła: <strong>".$config->wyszukaj."</strong>";
						
				$this->obj['logged'] = ( $objSession->IsLoggedIn()) ? 1: 0;
				
							
				tools::_assign('obj',$this->obj);
				tools::_display("{$this->tpl}Allegro/header_column_right.tpl");
				$this->listaOfertWyszukanych();
				tools::_display("{$this->tpl}Allegro/footer.tpl");
										
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");					
				break;
				
			case 'oferta':
				tools::_display("{$this->tpl}Allegro/header.tpl");
				$this->toolbar($toolbar_links3);
					$oferta = $this->getOferta( $this->opc[2]);	
					$this->obj['tytul'] =  $this->polozenieKategorii($oferta['categID']);												
					$this->obj['logged'] = ( $objSession->IsLoggedIn()) ? 1: 0;
					$this->sprawdzFotki($oferta['ofertaID'],$oferta['categID']);
					$this->pobierzPlikiOferty($oferta['categID'],$oferta['ofertaID']);
					// promocje	
					tools::_assign("oferty",$this->getListaOfertPromocyjnych(8/*limit*/,$oferta['ofertaID']));		
					tools::_assign('obj',$this->obj);
					tools::_assign('oferta',$oferta);
					tools::_display("{$this->tpl}Allegro/header_main.tpl");
					
					tools::_display("{$this->tpl}Allegro/jedna_oferta.tpl");
					
					tools::_display("{$this->tpl}Allegro/footer.tpl");
										
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");	
				
				break;
				
			case 'edytuj_oferte':
				if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				
				tools::_display("{$this->tpl}Allegro/header.tpl");
				$this->toolbar($toolbar_links4);
					$oferta = $this->getOferta( $this->opc[2],  $this->opc[3]);	
					$this->pobierzPlikiOferty($oferta['categID'],$oferta['ofertaID']);
					$this->obj['tytul'] =  $this->polozenieKategorii($oferta['categID']);					
					$this->obj['logged'] = ( $objSession->IsLoggedIn()) ? 1: 0;
								
					tools::_assign('obj',$this->obj);
					tools::_assign('oferta',$oferta);
					tools::_display("{$this->tpl}Allegro/header_main.tpl");
					
					tools::_display("{$this->tpl}Allegro/edytuj_oferte.tpl");
					
					tools::_display("{$this->tpl}Allegro/footer.tpl");
										
					tools::_display("{$this->tpl}Allegro/footer-main.tpl");	
				
				break;	
				
			case 'exportuj_oferte':	
				
				
				tools::_display("{$this->tpl}Allegro/header.tpl");
				if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") != 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				
				$this->toolbar($toolbar_links4);
					$oferta = $this->getOferta( $this->opc[2]);	
					$this->obj['tytul'] =  $this->polozenieKategorii($oferta['categID']);												
					$this->obj['logged'] = ( $objSession->IsLoggedIn()) ? 1: 0;
					
					$this->sprawdzFotki($oferta['ofertaID'],$oferta['categID']);
					// promocje	
					tools::_assign("oferty",$this->getListaOfertPromocyjnych(5,$oferta['ofertaID']));
					if(is_file($this->photoAllegroPath.'oferta.html')){	
						$fh = fopen($this->photoAllegroPath.'oferta.html', 'r+');
						$this->obj['export'] = fread($fh, filesize($this->photoAllegroPath.'oferta.html'));
					}						
							
					tools::_assign('obj',$this->obj);
					tools::_assign('oferta',$oferta);
					tools::_display("{$this->tpl}Allegro/header_main.tpl");
					
					$this->pokazKategorieAllegro($this->opc[2]);

					//tools::_display("{$this->tpl}Allegro/jedna_oferta.tpl");
					tools::_display("{$this->tpl}Allegro/footer.tpl");
										
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				

				break;
								
			case 'dodaj_oferte':
				tools::_display("{$this->tpl}Allegro/header.tpl");
				if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				$this->toolbar($toolbar_links0);
				$kategoria = $this->getCategory($this->opc[2],$config->__lang);
				$this->obj['categName'] = $kategoria['categName'];
				$this->obj['categID'] =  $this->opc[2];
				tools::_assign('obj',$this->obj);
				tools::_display("{$this->tpl}Allegro/dodaj_oferte.tpl");
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				break;

#TODO inne				
			case 'ustawienia_allegro':
				tools::_display("{$this->tpl}Allegro/header.tpl");
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
				$this->toolbar($toolbar_links0);
				tools::_display("{$this->tpl}Allegro/ustawienia.tpl");
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
				break;	
							
			default:
				tools::_display("{$this->tpl}Allegro/header.tpl");
				$this->toolbar($toolbar_links0);
				
					tools::_display("{$this->tpl}Allegro/header_column_left.tpl");
					$category_arr = $this->getCategory();
					$default_category = (is_array($category_arr) && !empty($category_arr)) ? $category_arr : null;
					AllegroModel::listaKategoriiUstawienia(0,0,$category_arr,"{$this->tpl}Allegro/tree.tpl");
					tools::_display("{$this->tpl}Allegro/footer.tpl");
					
					
					
					
					$promocje = $this->getListaOfertPromocyjnych();
					if(is_array($promocje) && !empty($promocje)){
						$promocje = $promocje;
						//$this->obj['tytul'] =  "Promocje";
						tools::_assign('obj',$this->obj);
						tools::_assign("oferty",$promocje);
						tools::_display("{$this->tpl}Allegro/header_column_right.tpl");
						tools::_display("{$this->tpl}Allegro/lista_ofert.tpl");
					
					}else if (is_array($category_arr) && !empty($category_arr)){
						$this->obj['tytul'] = $category_arr[0][5];
						tools::_assign('obj',$this->obj);
						tools::_display("{$this->tpl}Allegro/header_column_right.tpl");
						$this->listaOfert($category_arr[0]["categID"]);					
					}					
					tools::_display("{$this->tpl}Allegro/footer.tpl");
										
				tools::_display("{$this->tpl}Allegro/footer-main.tpl");
			
		}
	}
	
	
	public function kategorieAllegroAction(){
		$kategorie = $this->getCategory(null,null,false);
		AllegroModel::listaKategoriiUstawienia(0,0,$kategorie,"{$this->tpl}Allegro/tree_homepage.tpl");
	}

#TODO pomocnicze
	private function pobierzPlikiOferty($categID=null, $ofertaID=null){
		$file = new FilesController($this->photoAllegroPath,$categID.'_'.$ofertaID.'_');
		$group = $file->getFiles();
		if(!empty($group['photos']))tools::_assign('fFotos',$group['photos']);
		if(!empty($group['archiw']))tools::_assign('fArch',$group['archiw']);
		if(!empty($group['doc']))tools::_assign('fDoc',$group['doc']);
		if(!empty($group['video']))tools::_assign('fVideo',$group['video']);
		if(!empty($group['audio']))tools::_assign('fAudio',$group['audio']);
	}
	
	private function toolbar($tool__){
		global $objSession;
		tools::_assign("toolbar_links",$tool__);		
		if ( $objSession->IsLoggedIn() && $objSession->GetUserData("stanowisko") == 'a') tools::_display("{$this->tpl}Allegro/toolbar.tpl");
	}
	
	private function listaOfert($categID=null){
		tools::_assign("oferty",$this->getListaOfert($categID));
		tools::_display("{$this->tpl}Allegro/lista_ofert.tpl");
	}

	
	private function listaOfertWyszukanych(){
		tools::_assign("oferty",$this->getListaOfertWyszukiwarka());
		tools::_display("{$this->tpl}Allegro/lista_ofert.tpl");
	}
	
	private function sprawdzFotki($ofertaID,$categID){		
		for ($i=0;$i<=9;$i++){
			$this->obj['fotki'][$i] = is_file($this->photoAllegroPath."{$categID}_{$ofertaID}_{$i}_oferta_photo.jpg" );
		}		
	}
	
	private function usunThumbsFiles($categID,$ofertaID,$photoID){
		global $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		$file = "{$categID}_{$ofertaID}_{$photoID}_oferta_photo.jpg";
		$__thumbs = $this->pobierzListePlkowOferty($this->photoAllegroPath,$file);		
		foreach ($__thumbs as $__thumb){
			$this->usunPlikiZDysku($__thumb);
		}			
		$this->usunPlikiZDysku("{$this->photoAllegroPath}{$file}");
	}
	
	private function pokazKategorieAllegro($ofertaID){
		global $config;
		$this->pageID = $config->page;
		if ( $this->exp->connectToAllegroApi()){
	
			if ($this->exp->loginToAllegro()){
				$categoria_wybrana = (isset($this->opc[3]) ) ? $this->opc[3] : 0;
				$categoria_parent = (isset($this->opc[4]) ) ? $this->opc[4] : 0;
				
				
				$this->exp->pokazFormAllegro($categoria_wybrana, $categoria_parent, $this->opc[2]);
			}else{
				tools::_display("AllegroExport/login_allegro.tpl");
			}
			
		}else{
			tools::_display("AllegroExport/login_allegro.tpl");
		}
	}
	
	
	
#TODO zapis formularzy
	
	public function zapiszAukcjeAllegroAction(){
		$this->exp->loginToAllegro();
		$this->exp->zapiszAukcjeAllegro();		
	}
	
	public function zapiszNowaOferteAction(){
		global $config,$objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		$ofertaID = AllegroModel::zapiszNowaOferte();
		AllegroModel::zapiszZdjeciaOferty($ofertaID);
		tools::_redirect($config->page.",,lista_ofert,{$config->categID}.html",null,0,'php');
	}
	
	public function zapiszEdytowanaOferteAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		AllegroModel::zapiszEdytowanaOferte();
		AllegroModel::zapiszZdjeciaOferty($config->ofertaID);
		tools::_redirect($config->page.",,lista_ofert,{$config->categID}.html",null,0,'php');		
	}
	
	public function zapiszNowaKategorieAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		
		$categID = $this->saveNewCategory();
		AllegroModel::zapiszZdjeciaCategorii($categID);
		tools::_redirect($config->page.',,lista_kategorii.html',null,0,'php');
	}
	public function zapiszEdytowanaKategorieAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		
		$this->saveEditCategory();
		AllegroModel::zapiszZdjeciaCategorii($config->categID);
		tools::_redirect($config->page.',,lista_kategorii.html',null,0,'php');
	}
	
	public function usunKategorieAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}

		$this->usunKategorie($this->opc[2]);
		//tools::_redirect($config->page.',,lista_kategorii.html',null,0,'php');		
	}
	
	public function usunOferteKataloguAction($oferta_){
		global $config;
		$oferta = $this->getOferta( $this->opc[2]);	
		$this->usunOferte($oferta['categID'],$this->opc[2]);
		tools::_redirect($config->page.",,lista_ofert,{$oferta['categID']}.html",null,0,'php');
	}
	
	public function usunZdjecieAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		
		$this->usunThumbsFiles($this->opc[2],$this->opc[3],$this->opc[4]);
		tools::_redirect($config->page.",,edytuj_oferte,{$this->opc[3]}.html",null,0,"php");
	}
	public function zapiszUstawieniaAllegroAction(){
		global $config, $objSession;
		if ( !$objSession->IsLoggedIn()  && $objSession->GetUserData("stanowisko") == 'a'){	tools::_redirect('zaloguj_sie.html'); return;}
		
		$this->saveSettingsAllegro();
		tools::_redirect($config->page.",,lista_ofert,{$config->categID}.html",null,0,'php');
	}
	
	public function categUpAction(){
		global $config;
		$this->categoryLpUp($this->opc[2],$this->opc[3]);
		tools::_redirect($config->page.',,lista_kategorii.html',null,0,'php');
	}
	
	public function categDownAction(){
		global $config;
		$this->categoryLpDown($this->opc[2],$this->opc[3]);
		tools::_redirect($config->page.',,lista_kategorii.html',null,0,'php');
	}
	
	public function wyszukajOfertyAction(){
		$this->opc[1] = 'wyszukaj_oferty';
	}
	
	public function zapiszPlikiOfertyAction(){
		global $config;
		// zapis pliku: path, prefix_width_height_
		$file = new FilesController($this->photoAllegroPath,$config->categID.'_'.$config->ofertaID.'_');
		$file->saveFiles();	
		tools::_redirect($config->page.",,edytuj_oferte,{$config->ofertaID}.html",null,0,'php');
		
	}
}
